const User = require("../model/user.model");

class UserService {
  /**
   * 用户注册
   * @param {*} user_name 
   * @param {*} password 
   * @returns 
   */
  async register(user_name, password) {
    try {
      const res = await User.create({
        user_name,
        password,
      });
      return res.dataValues;
    } catch (error) {
      console.log(error);
    }
  }
  /**
   * 获取用户信息
   * @param {*} param0 
   * @returns 
   */
  async getUserInfo({ id, user_name, password, is_admin }) {
    const whereOpt = {};
    id && Object.assign(whereOpt, { id });
    user_name && Object.assign(whereOpt, { user_name });
    password && Object.assign(whereOpt, { password });
    is_admin && Object.assign(whereOpt, { is_admin });

    try {
      const res = await User.findOne({
        attributes: ["id", "user_name", "password", "is_admin"],
        where: whereOpt,
      });
      return res ? res.dataValues : null;
    } catch (error) {
      console.log(error);
    }
  }
  /**
   * 根据id更新用户信息
   * @param {*} param0 
   * @returns 
   */
  async updateById({ id, user_name, password, is_admin }) {
    const whereOpt = { id };
    const newUser = {};
    user_name && Object.assign(newUser, { user_name });
    password && Object.assign(newUser, { password });
    is_admin && Object.assign(newUser, { is_admin });
    try {
      const res = await User.update(newUser, { where: whereOpt });
      return res[0] > 0 ? true : false;
    } catch (error) {
      console.log(error);
    }
  }
}

module.exports = new UserService();
